package self.exception;

import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import self.enumerate.ResponseCode;
import self.result.R;
import java.sql.SQLException;

@ControllerAdvice
@Slf4j   //记录日志
public class GlobalException {  //这个类是用来处理全局异常的

    /**
     * 对BusinessException异常的全局处理
     * @param businessException
     * @return
     */
    @ExceptionHandler(BusinessException.class)
    @ResponseBody  //返回JSON格式
    public R handlerBusinessException(BusinessException businessException) {
        return R.error(businessException.getCode(), businessException.getMessage());
    }

    /**
     * 对SQLException异常的全局处理
     * @return
     */
    @ExceptionHandler(SQLException.class)
    @ResponseBody  //返回JSON格式
    public R handlerSQLException(SQLException sqlException) {
        return R.error(ResponseCode.SQL_EXCEPTION.getCode(), ResponseCode.SQL_EXCEPTION.getMessage());
    }

    /**
     * 对系统异常进行全局异常处理
     * @param exception
     * @return
     */
    @ExceptionHandler(Exception.class)
    @ResponseBody  //返回JSON格式
    public R handlerException(Exception exception) {
        //记录一下遇到的异常
        log.error("出现了系统异常：{}", exception.getMessage());
        return R.error(ResponseCode.SYSTEM_EXCEPTION.getCode(), ResponseCode.SYSTEM_EXCEPTION.getMessage());
    }

    /**
     * 用户没有权限访问的异常处理
     * @param accessDeniedException
     * @return
     */
    public R handleAccessDeniedException(AccessDeniedException accessDeniedException) {
        return R.error(ResponseCode.UNAUTHORIZATION_EXCEPTION.getCode(), ResponseCode.UNAUTHORIZATION_EXCEPTION.getMessage());
    }

}
